package com.keter.framework.core.util;

import com.google.common.base.Charsets;
import com.google.common.io.ByteStreams;
import com.google.common.io.Files;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Base64;
import java.util.zip.GZIPInputStream;

/**
 * 
 */
public class IOUtil {
    private static final Logger logger = LoggerFactory.getLogger(IOUtil.class);

    /**
     * <p>
     * Method ：ensureExists
     * <p>
     * Description : 确保路径存在
     *
     * @param path
     * @author 顾力行-gulixing@msn.com
     */
    public static String ensureExists(String path) {
        if (!new File(path).exists()) {
            boolean dir = new File(path).mkdirs();
            if(!dir){
                logger.error("无法创建目录:{}",path);
                throw new RuntimeException("目录["+path+"]创建失败！");
            }
        }
        return path;
    }
    
    public static boolean existsFile(String path) {
    	return new  File(path).exists();
    }

    public static boolean existsClassPathFile(String path) {
       return new ClassPathResource(path).exists();
    }

    public static byte[] toByteArray(File f) {
    	try {
			return Files.toByteArray(f);
		} catch (IOException e) {
			logger.error("",e);
		}
    	return null;
    }
    
    public String fileToString(String fileUri) {
    	try {
    		return Files.asCharSource(new File(fileUri), Charsets.UTF_8).read();
    	} catch (IOException e) {
			logger.error("",e);
    	}
    	return null;
    }
    
    public static long sizeOf(String fileUri) throws IOException {
          return sizeOf(new File(fileUri));
    }
    
    public static long sizeOf(File file) throws IOException {
		  return Files.asByteSource(file).size();
    }
    
    public static long bytesToMB(long bytes){
    	return bytes/1024/1024;
    }

    
    /**
     * <p>Method ：writeFile
     * <p>Description : 字节数组写入磁盘文件
     * @param b
     * @param outputFile 
     * @author  gulixing@msn.com
     * @version 1.0.0
     */
    public static void writeFile(byte[] b, String outputFile) {
    	try {
			Files.write(b, new File(outputFile));
		} catch (IOException e) {
			logger.error("",e);
		}
    }

    /**
     * 这玩意儿只支持ISO-8859-1
     * @param str
     * @return
     * @throws IOException
     */
    public static String decompressGzip(String str) throws IOException {
        ByteArrayInputStream in = new ByteArrayInputStream(str.getBytes("ISO-8859-1"));
        GZIPInputStream gunzip = new GZIPInputStream(in);
        return getOutputString(gunzip);
    }

    public static String decompressGzipBase64(String str) throws IOException {
        if (str == null || str.length() == 0) {
            return str;
        }
        GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(Base64.getDecoder().decode(str)));
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteStreams.copy(gis,out);
        return new String(out.toByteArray());
    }

    private static String getOutputString(GZIPInputStream gunzip) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteStreams.copy(gunzip,out);
        return out.toString();
    }


    /**
     * 获取当前jar/war包所在路径
     * 用于从相对路径查找配置文件等
     * @author gulixing@msn.com
     * @date   2016年1月5日
     */
    public static String getJarPath() {
        File file = new File("nonexist").getAbsoluteFile();
        try {
            return file.getParentFile().getCanonicalPath();
        } catch (IOException e) {
            logger.error("jar路径获取失败!",e);
        }
        throw new NullPointerException("jar路径获取失败!");
    }

//    public static void main(String[] args) throws IOException {
//        System.out.println(getJarPath());
//        System.out.println(MessageFormat.format("PathKit Root:{0}", PathKit.getRootClassPath()));
//        System.out.println(MessageFormat.format("IOUtil Root:{0}",IOUtil.getRootClassPath()));
//    	int a = 2,b=32;
//    	System.out.println(Math.pow(a,b));
//    	System.out.println(Math.pow(2.0,32));
//    	System.out.println(Files.asCharSource(new File("E:/git/keter/readme.md"), Charsets.UTF_8).read());
//    }
}